import loginView from '@/views/login'
import $ from 'jquery'
import { loginApi } from '@/model/userModel'

class LoginController {
  index(router) {
    return (req, res) => {
      res.render(loginView())

      $('#loginBtn').click(async function () {
        let formData = {}
        $('input').each(function (index, el) {
          formData[$(this).attr('name')] = $(this).val()
        })
        let ret = await loginApi(formData)
        console.log(ret)
        if (ret.code == 0) {
          // 登录成功把token记录到本地存储中
          sessionStorage.setItem('token', ret.data.token)
          sessionStorage.setItem('uid', ret.data.id)
          sessionStorage.setItem('username', ret.data.id)
          sessionStorage.setItem('nickname', ret.data.nickname)
          // 跳转
          router.go('/index')
        } else {
          alert('登录失败，请重新登录')
        }
      })
    }
  }
}

export default new LoginController()